﻿using rbac.domain.Entity;
using rbac.domain.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace rbac.domain.Impl
{
    public class RolePermissionRepository : IRolePermissionRepository
    {

        RbacContext _context;

        public RolePermissionRepository(RbacContext context)
        {
            _context = context;
        }

        public int DistributeRolePermission(int roleId, List<int> permissionIdList)
        {
            if (permissionIdList.Count < 0)
            {
                return 0;
            }
            //最新的权限列表
            List<RolePermission> list = permissionIdList.Select(p => new RolePermission
            {
                RoleId = roleId,
                PermissionId = p
            }).ToList();

            //查询原有的权限列表
            var oldPermissions = _context.RolePermissions.Where(x => x.RoleId == roleId);
            //移除原有的权限
            _context.RolePermissions.RemoveRange(oldPermissions);
            _context.RolePermissions.AddRange(list);

            //获取需要移除的列表
            //var needDeleteList=oldPermissions.Except(list);//取差集
            //_context.RolePermissions.RemoveRange(needDeleteList);
            //var needAddlist= list.Except(oldPermissions);//需要新增的权限
            //_context.RolePermissions.AddRange(needAddlist);

            return _context.SaveChanges();
        }


        /// <summary>
        /// 权限角色获取权限列表
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public List<Permission> GetPermissionByRoleId(int roleId)
        {
            //根据角色id获取权限id列表
            var permissionIdLiser= _context.RolePermissions.Where(x => x.RoleId == roleId).Select(x => x.PermissionId);

            //权限id list去permission表中获取详细数据
            var permissions = _context.Permissions.Where(x => permissionIdLiser.Contains(x.Id)).ToList();

            return permissions;
        }



    }
}
